package com.zline.foodraise.ui.activity;

import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.NoticeBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.js.MyWebViewSetting;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/11/23.
 * 公告详情
 */
@EActivity(R.layout.activity_detail_notice)
public class DetailNoticeActivity extends ZlineActivity {
    private static final String LOG_TAG = DetailNoticeActivity.class.getSimpleName();
    @ViewById(R.id.detail_notice_wv)
    WebView wv;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_iv;
    @ViewById(R.id.detail_notice_srl)
    SwipeRefreshLayout swipeRefreshLayout;
    MyWebViewSetting mSetting;
    @Extra
    NoticeBean noticeBean;
    //html 内容
    String content;
    //标题
    String title;
    //公告ID
    long noticeId;
    @Bean
    HttpUtil httpUtil;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpErro httpErro;
    int resultCode = 0;
    @Bean
    HttpDataParsing httpDataParsing;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.ex_no_data_rl)
    RelativeLayout no_data_rl;
    @Bean
    NetworkUtil networkUtil;
    //是否加载失败
    boolean loadFail = false;
    //第一次加载数据
    boolean firstLoad = true;

    @AfterViews
    void doSomeAfterViews() {
        initData();
        initTitle();
        initWebView();
        initSwipRefreshLayout();
        requestData();
    }

    void initData() {
        if (noticeBean != null) {
            title = noticeBean.getTitle();
            content = noticeBean.getContent();
            noticeId = noticeBean.getNoticeId();
        }
    }

    void initTitle() {
        title_iv.setText(title);
    }

    void initWebView() {
        mSetting = new MyWebViewSetting(wv, this);
        mSetting.setWebView();
        wv.setWebViewClient(new WebViewClient() {
            //出错界面
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                LUtil.i(LOG_TAG, "______________erroCode________" + description);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LUtil.i(LOG_TAG, "_________shouldOverrideUrlLoading________" + url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                LUtil.i(LOG_TAG, "_________onPageStarted________" + url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LUtil.i(LOG_TAG, "____Host_____onPageFinished________" + url);
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }
            }
        });
    }


    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (networkUtil.isNetworkAvailable()) {
                    requestDetailNotice();
                } else {
                    stopRefresh();
                    TUtil.showShort(DetailNoticeActivity.this, R.string.no_network);
                }

            }
        });
    }

    //请求数据
    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            requestDetailNotice();
        } else {
            showLoadFailView(true);
            TUtil.showShort(this, R.string.no_network);
        }
    }

    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        loadFail = isException;
        if (isException) {
            exception_fl.setVisibility(View.VISIBLE);
            exception_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            exception_rl.setVisibility(View.GONE);
        }
    }

    //是否显示暂无数据
    void showNoDataView(boolean noData) {
        if (noData) {
            exception_fl.setVisibility(View.VISIBLE);
            no_data_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            no_data_rl.setVisibility(View.GONE);
        }
    }


    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    //请求活动公告列表
    void requestDetailNotice() {
        httpOperator.requestNoticeInfo(httpUtil, noticeId, requestNoticeInfoHandler);
    }


    //获取活动公告列表回调
    AsyncHttpResponseHandler requestNoticeInfoHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestNoticeListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        noticeBean = httpDataParsing.getNoticeInfo(response);
                        setWebContent(noticeBean);
                    } else {
                        if (firstLoad) {
                            showLoadFailView(true);
                        } else {
                            httpErro.showCommonErroResult(resultCode);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    firstLoad = false;
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
            if (firstLoad) {
                showLoadFailView(true);
            }
            firstLoad = false;
            stopRefresh();

        }
    };


    void setWebContent(NoticeBean noticeBean) {
        stopRefresh();
        if (noticeBean == null) return;
        content = noticeBean.getContent();
        wv.loadData(content, "text/html; charset=UTF-8", null);
        if (StringUtils.isEmpty(content)) {
            showNoDataView(true);
        } else {
            showNoDataView(false);
        }


    }


    @Click({R.id.app_common_header_left_icon_iv, R.id.reload_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.reload_tv:
                requestData();
                break;
            default:
                break;
        }
    }

}
